import json
import math

from fastapi import APIRouter, Request, Depends
from fastapi.templating import Jinja2Templates
from flask import request
from mysql.connector import cursor

from src.db import get_db

app01 = APIRouter()

templates = Jinja2Templates(directory="templates")


@app01.get("/user_list")
def user_list(db: cursor.MySQLCursor = Depends(get_db)):
    p = request.args.get("p", '')  # 页数
    show_shouye_status = 0  # 显示首页状态
    if p == '':
        p = 1
    else:
        p = int(p)
        if p > 1:
            show_shouye_status = 1

    limit_start = (int(p) - 1) * 10  # 起始

    sql = "select * from s_id_detail limit {0},10".format(limit_start)
    user_list = db.getMany(sql)

    sql = "select count(id) as total from s_id_detail"
    count = db.getOne(sql)['total']  # 总记录
    total = int(math.ceil(count / 10.0))  # 总页数

    dic = get_page(total, p)
    datas = {
        'user_list': user_list,
        'p': int(p),
        'total': total,
        'show_shouye_status': show_shouye_status,
        'dic_list': dic
    }
    print(datas)
    return templates.TemplateResponse(
        'user_list.html',
        {
            'request': request,  # 注意，返回模板响应时，必须有request键值对，且值为Request请求对象
            'datas': datas,
        })


def get_page(total, p):
    """get page 封装"""
    show_page = 5  # 显示的页码数
    pageoffset = 2  # 偏移量
    start = 1  # 分页条开始
    end = total  # 分页条结束

    if total > show_page:
        if p > pageoffset:
            start = p - pageoffset
            if total > p + pageoffset:
                end = p + pageoffset
            else:
                end = total
        else:
            start = 1
            if total > show_page:
                end = show_page
            else:
                end = total
        if p + pageoffset > total:
            start = start - (p + pageoffset - end)
    # 用于模版中循环
    dic = range(start, end + 1)
    return dic


@app01.get('/')
async def hello(request: Request, db: cursor.MySQLCursor = Depends(get_db)):
    current_list = await get_list(db)
    ret_data = json.loads(current_list)
    print(json.loads(current_list))
    return templates.TemplateResponse(
        'index.html',
        {
            'request': request,  # 注意，返回模板响应时，必须有request键值对，且值为Request请求对象
            'itemData': '',
        }
    )


@app01.get('/get_content')
async def _get_content(request: Request, db: cursor.MySQLCursor = Depends(get_db)):
    current_list = await get_list(db)
    ret_data = json.loads(current_list)
    print(json.loads(current_list))
    return templates.TemplateResponse(
        'index.html',
        {
            'request': request,  # 注意，返回模板响应时，必须有request键值对，且值为Request请求对象
            'itemData': ret_data,
        }
    )


def fetch_dict_result(cur):
    row_headers = [x[0] for x in cur.description]  # this will extract row headers
    rv = cur.fetchall()
    json_data = []
    for result in rv:
        json_data.append(dict(zip(row_headers, result)))
    return json.dumps(json_data, ensure_ascii=False)


@app01.get('/list')
async def get_list(db: cursor.MySQLCursor = Depends(get_db)):
    query = "select * from medicine_info"
    db.execute(query)
    json_str = fetch_dict_result(db)
    print(json_str)
    return json_str


@app01.get("/user/{id}")
def get_user(id):
    # id = 1
    print("id", id, type(id))
    return {
        "user_id": id
    }


@app01.get("/articles/{id}")
def get_article(id: int):
    # id = 1
    print("id", id, type(id))
    return {
        "article_id": id
    }
